package com.masterclient.app.modules.aftersale;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselibrary.bean.aftersale.ReturnGoodsBean;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsContract;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsPresenter;
import com.eoner.uikit.dialog.simple.ChooseHeadImgDialog;
import com.masterclient.app.widget.PriceIntegralLayout;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import top.zibin.luban.Luban;

import static com.masterclient.app.modules.aftersale.AfterSaleDetailActivity.NEW_AFTERSALE;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.IMAGE_PICKER;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.REQUEST_CODE_SELECT;

/**
 * 作者：sean
 * 创建时间：2017/7/28 10:15
 * 功能说明：
 */

public class ReturnMoneyActivity extends BaseActivity<ReturnGoodsPresenter> implements ReturnGoodsContract.View {


    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.v_head)
    View vHead;
    @BindView(R.id.tv_return_reason)
    TextView tvReturnReason;
    @BindView(R.id.tv_reason)
    TextView tvReason;
    @BindView(R.id.rl_choose_reason)
    RelativeLayout rlChooseReason;
    @BindView(R.id.ll_price)
    PriceIntegralLayout llPrice;
    @BindView(R.id.tv_ship_fee)
    TextView tvShipFee;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.tv_hb)
    TextView tvHb;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.ll_dfh)
    LinearLayout llDfh;
    @BindView(R.id.tv_payment_name)
    TextView tvPaymentName;
    @BindView(R.id.et_third_return)
    EditText etThirdReturn;
    @BindView(R.id.tv_most_return)
    TextView tvMostReturn;
    @BindView(R.id.rl_third)
    RelativeLayout rlThird;
    @BindView(R.id.et_hb_return)
    EditText etHbReturn;
    @BindView(R.id.tv_mosthb_return)
    TextView tvMosthbReturn;
    @BindView(R.id.rl_hb)
    RelativeLayout rlHb;
    @BindView(R.id.et_balance_return)
    EditText etBalanceReturn;
    @BindView(R.id.tv_mostbalance_return)
    TextView tvMostbalanceReturn;
    @BindView(R.id.rl_balance)
    RelativeLayout rlBalance;
    @BindView(R.id.ll_yfh)
    LinearLayout llYfh;
    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.rl_add_img)
    RelativeLayout rlAddImg;
    @BindView(R.id.gridLayout)
    GridLayout gridLayout;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_third_pay)
    TextView tvThirdPay;
    @BindView(R.id.rl_third_pay)
    RelativeLayout rlThirdPay;
    //    @BindView(R.id.v_line1)
//    View vLine1;
    @BindView(R.id.tv_hb_tag)
    TextView tvHbTag;
    @BindView(R.id.rl_hb_pay)
    RelativeLayout rlHbPay;
    //    @BindView(R.id.v_line2)
//    View vLine2;
    @BindView(R.id.tv_cash_tag)
    TextView tvCashTag;
    @BindView(R.id.rl_cash_pay)
    RelativeLayout rlCashPay;
    @BindView(R.id.tv_integral)
    TextView tvIntegral;
    @BindView(R.id.tv_integral_tag)
    TextView tvIntegralTag;
    @BindView(R.id.rl_integral_pay)
    RelativeLayout rlIntegralPay;
    @BindView(R.id.return_money_remark)
    TextView returnMoneyRemark;
    @BindView(R.id.tv_shipment_choose)
    TextView tvShipmentChoose;
    @BindView(R.id.tv_shipment)
    TextView tvShipment;
    @BindView(R.id.rl_shipment_choose)
    RelativeLayout rlShipmentChoose;
    @BindView(R.id.et_integral_return)
    EditText etIntegralReturn;
    @BindView(R.id.tv_mostintegral_return)
    TextView tvMostintegralReturn;
    @BindView(R.id.rl_integral)
    RelativeLayout rlIntegral;
    @BindView(R.id.tv_integral_deduction)
    TextView tvIntegralDeduction;
    @BindView(R.id.rl_integral_pay_deduction)
    RelativeLayout rlIntegralPayDeduction;
    @BindView(R.id.et_integral_return_deduction)
    EditText etIntegralReturnDeduction;
    @BindView(R.id.tv_mostintegral_return_deduction)
    TextView tvMostintegralReturnDeduction;
    @BindView(R.id.rl_integral_deduction)
    RelativeLayout rlIntegralDeduction;
    @BindView(R.id.return_money_giveaway)
    TextView returnMoneyGiveaway;

    @BindView(R.id.layout_freight)
    View layoutFreight;
    @BindView(R.id.tv_freight_price)
    PriceIntegralLayout tvFreightPrice;
    @BindView(R.id.tv_freight_desc)
    TextView tvFreightDesc;
    @BindView(R.id.tv_freight_check)
    CheckBox tvFreightCheck;

    private ChooseHeadImgDialog headImgDialog;
    ImagePicker imagePicker;
    private ReturnGoodsBean.DataBean dataBean;
    private ReturnGoodsBean.DataBean.ShProductBean shProductBean;

    private SetAliPayDialog returnDialog;
    private ReturnReasonDialog returnReasonDialog, returnShipmentDialog;

    private List<UploadImgBean.DataBean> images = new ArrayList<>();
    private List<File> fileList;

    double pay_price, redPack, balance;
    long integral = 0,integralDeduction = 0;
    private String resean_id = "", receive_status = "",refund_reason_id,refund_type_id;
    private String product_id;
    private String order_id;
    private static final int IMAGE_SIZE = 9;

    private String update = "",fromType;
    private double mostPay_price = 0f, mostRedPack = 0f, mostBalance = 0f;
    private long mostIntegral = 0, mostIntegralDeduction = 0;
    private RxPermissions rxPermissions;
    private int imageHeight;
    private int receiveIndex;
    private List<ReturnGoodsBean.DataBean.ShReasonBean> reasonList ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_money);
        ButterKnife.bind(this);
        receiveIndex = 0;

        returnMoneyRemark.setText(Html.fromHtml("<font color=#F23051>注：</font>支付仅支持原路返回；余额支付返还余额；支付宝或微信支付，返还至付款账户（如有混合支付，返还至各自账户内）。"));
        rxPermissions = new RxPermissions(getActivity());
        reasonList = new ArrayList<>();

        product_id = getBundleString("product_id");
        update = getBundleString("update");
        order_id = getBundleString("order_id");fromType = getBundleString("from_type");
        if (TextUtils.isEmpty(fromType)){
            fromType = "";
        }
        if ("purchase".equals(fromType)){
            tvSubmit.setBackgroundResource(R.drawable.shape_round_ff6809);
        }
        mPresenter.setFromType(fromType);

        mPresenter.preAfterSale("refundApplyBase", product_id, update, order_id);
//        Utils.setDin(tvAllReturn,this);

        returnDialog = new SetAliPayDialog(mContext);

        imageHeight = ((int) ((ScreenUtils.getScreenWidth()-ScreenUtils.dp2px(23))/4f))-ScreenUtils.dp2px(9);
        headImgDialog = new ChooseHeadImgDialog(mContext, "上传图片", "相册", "拍照");
        headImgDialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
            @Override
            public void album() {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }

            @SuppressLint("CheckResult")
            @Override
            public void photo() {
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });
            }
        });

        imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(9);


        etHbReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etHbReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etHbReturn.addTextChangedListener(new MyTextWatcher());

        etThirdReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etThirdReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etThirdReturn.addTextChangedListener(new MyTextWatcher());

        etBalanceReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etBalanceReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etBalanceReturn.addTextChangedListener(new MyTextWatcher());

        etIntegralReturn.addTextChangedListener(new MyTextWatcher());
        etIntegralReturnDeduction.addTextChangedListener(new MyTextWatcher());

        /*etHbReturn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    if(TextUtils.isEmpty(etHbReturn.getText().toString().trim())||".".equals()){

                    }else {

                    }
                    buyNum = Integer.valueOf();
                }
            }
        });*/
    }

    public class MyInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(".") && dest.toString().length() == 0) {
                return "0.";
            }
            if (dest.toString().contains(".")) {
                int index = dest.toString().indexOf(".");
                int mlength = dest.toString().substring(index).length();
                if (mlength == 3) {
                    return "";
                }
            }
            return null;
        }
    }

    public class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            double all_price = 0;
            String hb = etHbReturn.getText().toString().trim();
            String third = etThirdReturn.getText().toString().trim();
            String balance = etBalanceReturn.getText().toString().trim();
            String integral = etIntegralReturn.getText().toString().trim();
            String integralDeduction = etIntegralReturnDeduction.getText().toString().trim();
            if (hb.endsWith(".") || third.endsWith(".") || balance.endsWith(".")) return;


            if (mostRedPack>0&&!TextUtils.isEmpty(hb)&&Double.parseDouble(hb)-mostRedPack>0.009){
                etHbReturn.setText(StringsUtils.keep2num(mostRedPack+""));
                etHbReturn.setSelection(StringsUtils.keep2num(mostRedPack+"").length());
                hb = mostRedPack+"";
            }
            if (mostPay_price>0&&!TextUtils.isEmpty(third)&&Double.parseDouble(third)-mostPay_price>0.009){
                etThirdReturn.setText(StringsUtils.keep2num(mostPay_price+""));
                etThirdReturn.setSelection(StringsUtils.keep2num(mostPay_price+"").length());
                third = mostPay_price+"";
            }
            if (mostBalance>0&&!TextUtils.isEmpty(balance)&&Double.parseDouble(balance)-mostBalance>0.009){
                etBalanceReturn.setText(StringsUtils.keep2num(mostBalance+""));
                etBalanceReturn.setSelection(StringsUtils.keep2num(mostBalance+"").length());
                balance = mostBalance+"";
            }
            if (mostIntegral>0&&!TextUtils.isEmpty(integral)&&Long.parseLong(integral)-mostIntegral>=1){
                etIntegralReturn.setText(mostIntegral+"");
                etIntegralReturn.setSelection((mostIntegral+"").length());
                integral = mostIntegral+"";
            }
            if (mostIntegralDeduction>0&&!TextUtils.isEmpty(integralDeduction)&&Long.parseLong(integralDeduction)-mostIntegralDeduction>=1){
                etIntegralReturnDeduction.setText(mostIntegralDeduction+"");
                etIntegralReturnDeduction.setSelection((mostIntegralDeduction+"").length());
                integralDeduction = mostIntegralDeduction+"";
            }

            if (!TextUtils.isEmpty(hb) && (!hb.startsWith(".") || hb.endsWith("."))) {
                all_price += Double.valueOf(hb);
            }

            if (!TextUtils.isEmpty(third) && (!third.startsWith(".") || third.endsWith("."))) {
                all_price += Double.valueOf(third);

            }

            if (!TextUtils.isEmpty(balance) && (!balance.startsWith(".") || balance.endsWith("."))) {
                all_price += Double.valueOf(balance);
            }
            llPrice.setData((TextUtils.isEmpty(integral)?0:Long.parseLong(integral)) +
                    (TextUtils.isEmpty(integralDeduction)?0:Long.parseLong(integralDeduction))+"",
                    StringsUtils.keep2num(String.valueOf(all_price)));

//            Utils.set_price_style(ReturnMoneyActivity.this,tvAllReturn,11,(TextUtils.isEmpty(integral)?0:Long.parseLong(integral))
//                    +(TextUtils.isEmpty(integralDeduction)?0:Long.parseLong(integralDeduction))+"",StringUtils.keep2num(String.valueOf(all_price)));

//            tvAllReturn.setText(StringUtils.keep2num(String.valueOf(all_price)) + ((TextUtils.isEmpty(integral)||TextUtils.isEmpty(integralDeduction)
//                    || (Long.parseLong(integral)+Long.parseLong(integralDeduction)) == 0) ? "" : ("+" + (Long.parseLong(integral)+Long.parseLong(integralDeduction)) + "金币")));
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @Override
    protected void onPause() {
        hideSoftInput(etDesc);
        super.onPause();
    }

    @OnClick({R.id.rl_back, R.id.rl_add_img, R.id.rl_shipment_choose, R.id.rl_choose_reason, R.id.tv_submit,R.id.layout_freight})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_freight:
                tvFreightCheck.setChecked(!tvFreightCheck.isChecked());
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_add_img:
                if (images == null) {
                    imagePicker.setSelectLimit(IMAGE_SIZE);
                } else {
                    imagePicker.setSelectLimit(IMAGE_SIZE - images.size());
                }
                headImgDialog.show();
                break;
            case R.id.rl_choose_reason:

                if (dataBean == null || dataBean.getSh_new_reason() == null ||dataBean.getSh_new_reason().getSh_refund()==null) return;

                if (rlShipmentChoose.getVisibility() == View.VISIBLE && TextUtils.isEmpty(receive_status)) {
                    showToast("请选择是否收到货");
                    return;
                }
                returnReasonDialog = new ReturnReasonDialog(mContext);
                returnReasonDialog.setOnConfirmListener(new ReturnReasonDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(int index) {
                        resean_id = reasonList.get(index).getSh_relation_id();
                        refund_reason_id = reasonList.get(index).getSh_refund_reason_id();
                        refund_type_id = reasonList.get(index).getSh_refund_type_id();
                        tvReason.setText(reasonList.get(index).getSh_reason_name());
                    }
                });
                returnReasonDialog.show();
                returnReasonDialog.setList(reasonList);
                break;
            case R.id.rl_shipment_choose:
                if (dataBean == null) return;
                returnShipmentDialog = new ReturnReasonDialog(mContext);
                returnShipmentDialog.setOnConfirmListener(new ReturnReasonDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(int index) {
                        receiveIndex = index;
                        reasonList = index == 0 ?dataBean.getSh_new_reason().getSh_refund().getSh_no_received():dataBean.getSh_new_reason().getSh_refund().getSh_is_received();
                        if (!dataBean.getSh_receive_status_list().get(index).getSh_status_id().equals(receive_status)){
                            tvReason.setText("请选择");
                            resean_id = "";
                        }
                        receive_status = dataBean.getSh_receive_status_list().get(index).getSh_status_id();
                        tvShipment.setText(dataBean.getSh_receive_status_list().get(index).getSh_status_text());

                    }
                });
                returnShipmentDialog.show();
                returnShipmentDialog.setReceiveList(dataBean.getSh_receive_status_list());
                break;
            case R.id.tv_submit:

                if (dataBean == null) return;

                if (rlShipmentChoose.getVisibility() == View.VISIBLE && TextUtils.isEmpty(receive_status)) {
                    showToast("请选择是否收到货");
                    return;
                }
                if (TextUtils.isEmpty(resean_id)) {
                    showToast("请选择退款原因");
                    return;
                }
                List<String> imageStrs = new ArrayList<>();
                if (images != null) {
                    for (UploadImgBean.DataBean dataBean : images) {
                        imageStrs.add(dataBean.getSh_image_url());
                    }
                }

                if (dataBean.getSh_product() != null && !TextUtils.isEmpty(dataBean.getSh_product().getSh_balance())) {
                    String returnMoney = etThirdReturn.getText().toString().trim();
                    String returnHb = etHbReturn.getText().toString().trim();
                    String returnBalance = etBalanceReturn.getText().toString().trim();
                    String returnIntegral = etIntegralReturn.getText().toString().trim();
                    String returnIntegralDeduction = etIntegralReturnDeduction.getText().toString().trim();

                    if (TextUtils.isEmpty(returnMoney) || TextUtils.isEmpty(returnHb) || TextUtils.isEmpty(returnBalance) ||
                            TextUtils.isEmpty(returnIntegral)||TextUtils.isEmpty(returnIntegralDeduction)) {
                        showToast("金额不能为空");
                        return;
                    }
                    if (returnMoney.endsWith(".") || returnMoney.startsWith(".") || returnHb.endsWith(".")
                            || returnHb.startsWith(".") || returnBalance.startsWith(".") || returnBalance.endsWith(".")) {
                        showToast("请输入正确的金额格式");
                        return;
                    }

                    redPack = Double.parseDouble(returnHb);
                    pay_price = Double.parseDouble(returnMoney);
                    balance = Double.parseDouble(returnBalance);
                    integral = Long.parseLong(returnIntegral);
                    integralDeduction = Long.parseLong(returnIntegralDeduction);

                    llPrice.setData(integral+integralDeduction+"",StringsUtils.keep2num((redPack + pay_price + balance)+""));

                } else {
                    redPack = Double.parseDouble(tvHb.getText().toString());
                    pay_price = Double.parseDouble(tvZfb.getText().toString());
                    balance = Double.parseDouble(tvBalance.getText().toString());
                    integral = Long.parseLong(tvIntegral.getText().toString());
                    integralDeduction = Long.parseLong(tvIntegralDeduction.getText().toString());
                }

//                if (isFastClick()) {
//                    showToast("操作过于频繁，请稍后再试");
//                    return;
//                }

                show_progressDialog();

                mPresenter.applyAfterSale(String.valueOf(integral), receive_status, StringsUtils.keep2num(String.valueOf(balance)), StringsUtils.keep2num(String.valueOf(redPack)), etDesc.getText().toString().trim(),
                        imageStrs, product_id, "", resean_id, "0", StringsUtils.keep2num(String.valueOf(pay_price)), update, order_id,integralDeduction+"",
                        "","refundApplyPut",null,refund_reason_id,refund_type_id,
                        layoutFreight.getVisibility()!=View.VISIBLE?"":(tvFreightCheck.isChecked()?"1":"0"));
                break;
        }
    }

    List<File> imageFileList;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {//相册
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImages(images);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImages(images);
            }
        }
    }

    @SuppressLint("CheckResult")
    private void uploadImages(ArrayList<ImageItem> images) {
        List<File> files = new ArrayList<>();
        for (ImageItem item : images) {
            File imgFile = new File(item.path);
            files.add(imgFile);
        }
//                mPresenter.uploadImage(files,"customer");
        if (files.size() > 0) {
            if (imageFileList == null) {
                imageFileList = new ArrayList<>();
            }
            //压缩并更新视图,上传图片
            Observable.fromIterable(files).map(new Function<File, File>() {
                @Override
                public File apply(@NonNull File file) throws Exception {
                    if (file != null) {
                        return Luban.with(mContext).load(file).get();
                    }
                    return null;
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                @Override
                public void accept(@NonNull File file) throws Exception {
                    if (file != null) {
                        imageFileList.add(file);

                        if (IMAGE_SIZE <= imageFileList.size()) {
                            rlAddImg.setVisibility(View.GONE);
                        }

                        View imageItem = View.inflate(mContext, R.layout.item_img, null);
                        ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageView.getLayoutParams().height = imageHeight;
                        imageView.getLayoutParams().width = imageHeight;
                        ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                        iv_delete.setTag(file.getName() + ".jpeg");
                        iv_delete.setOnClickListener(v -> {
                            gridLayout.removeView(imageItem);
                            imageFileList.remove(file);
//                            if (IMAGE_SIZE > imageFileList.size()) {
                                rlAddImg.setVisibility(View.VISIBLE);
//                            }
                            removeImage((String) iv_delete.getTag());
                        });

                        gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                        ViewTransformUtil.glideImageView(ReturnMoneyActivity.this, file.toURI().toURL().toString(), imageView, new Transformation[]{
                                new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);
//                        GlideUtil.displayImage(ReturnMoneyActivity.this, file.getAbsolutePath(), imageView, R.mipmap.defaults);
//                        App.picasso.load(file).into(imageView);
                        mPresenter.uploadImage(file, "review ", file.getName() + ".jpeg");
                    }
                }
            });
        }
    }

    @Override
    public void preAfterSaleInfo(ReturnGoodsBean.DataBean dataBean) {
        this.dataBean = dataBean;
        if (dataBean.getSh_gift_no_send_refund_remark() != null && dataBean.getSh_gift_no_send_refund_remark().length() > 0){
            returnMoneyGiveaway.setVisibility(View.VISIBLE);
            returnMoneyGiveaway.setText(dataBean.getSh_gift_no_send_refund_remark());
        }
        if (dataBean.getSh_refund_remark() != null && dataBean.getSh_refund_remark().length() > 0)
            returnMoneyRemark.setText(Html.fromHtml("<font color=#F23051>注：</font>" + dataBean.getSh_refund_remark()));

        if (dataBean.getSh_order() != null && !TextUtils.isEmpty(dataBean.getSh_order().getSh_balance())) {
            rlShipmentChoose.setVisibility(View.GONE);

            reasonList = dataBean.getSh_new_reason().getSh_refund().getSh_no_received();

            llPrice.setData((TextUtils.isEmpty(dataBean.getSh_order().getSh_integral())?0:Long.parseLong(dataBean.getSh_order().getSh_integral()))
                    +(TextUtils.isEmpty(dataBean.getSh_order().getSh_integral_deduction())?0:Long.parseLong(dataBean.getSh_order().getSh_integral_deduction()))+"",
                    StringsUtils.keep2num(dataBean.getSh_order().getSh_refund_price()));
//            Utils.set_price_style(ReturnMoneyActivity.this,tvAllReturn,11,(TextUtils.isEmpty(dataBean.getSh_order().getSh_integral())?0:Long.parseLong(dataBean.getSh_order().getSh_integral()))
//                    +(TextUtils.isEmpty(dataBean.getSh_order().getSh_integral_deduction())?0:Long.parseLong(dataBean.getSh_order().getSh_integral_deduction()))+"",StringUtils.keep2num(dataBean.getSh_order().getSh_refund_price()));

//            tvAllReturn.setText(dataBean.getSh_order().getSh_refund_price() + ((TextUtils.isEmpty(dataBean.getSh_order().getSh_integral())
//                    ||TextUtils.isEmpty(dataBean.getSh_order().getSh_integral_deduction())
//                    || (Long.parseLong(dataBean.getSh_order().getSh_integral())+Long.parseLong(dataBean.getSh_order().getSh_integral_deduction())) == 0)
//                    ? "" : ("+" + (Long.parseLong(dataBean.getSh_order().getSh_integral())+Long.parseLong(dataBean.getSh_order().getSh_integral_deduction())) + "金币")));
            if (Float.valueOf(dataBean.getSh_order().getSh_shipping_amount()) > 0) {
                tvShipFee.setText("（含快递费" + dataBean.getSh_order().getSh_shipping_amount() + "元）");
            }
            llYfh.setVisibility(View.GONE);
            llDfh.setVisibility(View.VISIBLE);

            if (Float.parseFloat(dataBean.getSh_order().getSh_should_pay_price()) > 0) {
                rlThirdPay.setVisibility(View.VISIBLE);
                tvThirdPay.setText( dataBean.getSh_payment_name() + ": ");
                tvZfb.setText( /*"¥" +*/ dataBean.getSh_order().getSh_should_pay_price());
            } else {
                rlThirdPay.setVisibility(View.GONE);
            }
            if (Float.parseFloat(dataBean.getSh_order().getSh_bupiao()) > 0) {
                tvHb.setText(/*"¥" +*/ dataBean.getSh_order().getSh_bupiao());
                rlHbPay.setVisibility(View.VISIBLE);
            } else {
                rlHbPay.setVisibility(View.GONE);
            }

            if (Float.parseFloat(dataBean.getSh_order().getSh_balance()) > 0) {
                rlCashPay.setVisibility(View.VISIBLE);
                tvBalance.setText(/*"¥" + */dataBean.getSh_order().getSh_balance());
            } else {
                rlCashPay.setVisibility(View.GONE);
            }
            if (Float.parseFloat(dataBean.getSh_order().getSh_integral()) > 0) {
                rlIntegralPay.setVisibility(View.VISIBLE);
                tvIntegral.setText(/*"¥" + */dataBean.getSh_order().getSh_integral());
            } else {
                rlIntegralPay.setVisibility(View.GONE);
            }

            if (Float.parseFloat(dataBean.getSh_order().getSh_integral_deduction()) > 0) {
                rlIntegralPayDeduction.setVisibility(View.VISIBLE);
                tvIntegralDeduction.setText(/*"¥" + */dataBean.getSh_order().getSh_integral_deduction());
            } else {
                rlIntegralPayDeduction.setVisibility(View.GONE);
            }


        } else {
            if (dataBean.getSh_product() != null&& !TextUtils.isEmpty(dataBean.getSh_product().getSh_balance())) {
                shProductBean = dataBean.getSh_product();

                rlShipmentChoose.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(shProductBean.getSh_shipping_amount())&&Float.valueOf(shProductBean.getSh_shipping_amount()) > 0) {
                    tvShipFee.setText("(含快递费" + shProductBean.getSh_shipping_amount() + "元)");
                }
//                llYfh.setVisibility(View.GONE);
//                llDfh.setVisibility(View.VISIBLE);
//                if (dataBean.getSh_order() != null) {
//                    if ("1".equals(dataBean.getSh_order().getSh_refund_price())) {
//
//
//                        pay_price = Float.parseFloat(shProductBean.getSh_should_pay_price_avg());
//                        redPack = Float.parseFloat(shProductBean.getSh_bupiao_avg());
//                        balance = Float.parseFloat(shProductBean.getSh_balance_avg());
//
//                        tvAllReturn.setText(dataBean.getSh_product().getSh_refund_price());
//                        if (Float.parseFloat(shProductBean.getSh_should_pay_price()) > 0) {
//                            rlThirdPay.setVisibility(View.VISIBLE);
//                            tvThirdPay.setText("·" + dataBean.getSh_payment_name() + ": ");
//                            tvZfb.setText( /*"¥" +*/ shProductBean.getSh_should_pay_price());
//                        } else {
//                            rlThirdPay.setVisibility(View.GONE);
//                        }
//                        if (Float.parseFloat(shProductBean.getSh_bupiao()) > 0) {
//                            tvHb.setText(/*"¥" +*/ shProductBean.getSh_bupiao());
//                            rlHbPay.setVisibility(View.VISIBLE);
//                        } else {
//                            rlHbPay.setVisibility(View.GONE);
//                        }
//
//                        if (Float.parseFloat(shProductBean.getSh_balance()) > 0) {
//                            rlCashPay.setVisibility(View.VISIBLE);
//                            tvBalance.setText(/*"¥" + */shProductBean.getSh_balance());
//                        } else {
//                            rlCashPay.setVisibility(View.GONE);
//                        }
//
//                    } else {
                llYfh.setVisibility(View.VISIBLE);
                llDfh.setVisibility(View.GONE);

                mostPay_price = Double.parseDouble(shProductBean.getSh_should_pay_price());
                mostRedPack = Double.parseDouble(shProductBean.getSh_bupiao());
                mostBalance = Double.parseDouble(shProductBean.getSh_balance());
                mostIntegral = Long.parseLong(shProductBean.getSh_integral());
                mostIntegralDeduction = Long.parseLong(shProductBean.getSh_integral_deduction());
                if (mostRedPack == 0) {
                    rlHb.setVisibility(View.GONE);
                }
                if (mostPay_price == 0) {
                    rlThird.setVisibility(View.GONE);
                }

                if (mostBalance == 0) {
                    rlBalance.setVisibility(View.GONE);
                }
                if (mostIntegral == 0) {
                    rlIntegral.setVisibility(View.GONE);
                }
                if (mostIntegralDeduction == 0) {
                    rlIntegralDeduction.setVisibility(View.GONE);
                }

                tvPaymentName.setText(dataBean.getSh_payment_name());

                llPrice.setData((TextUtils.isEmpty(shProductBean.getSh_integral())?0:Long.parseLong(shProductBean.getSh_integral()))
                        +(TextUtils.isEmpty(shProductBean.getSh_integral_deduction())?0:Long.parseLong(shProductBean.getSh_integral_deduction()))+"",
                        StringsUtils.keep2num(shProductBean.getSh_refund_price()));
//                Utils.set_price_style(ReturnMoneyActivity.this,tvAllReturn,11,(TextUtils.isEmpty(shProductBean.getSh_integral())?0:Long.parseLong(shProductBean.getSh_integral()))
//                        +(TextUtils.isEmpty(shProductBean.getSh_integral_deduction())?0:Long.parseLong(shProductBean.getSh_integral_deduction()))+"",StringUtils.keep2num(shProductBean.getSh_refund_price()));
//                tvAllReturn.setText(shProductBean.getSh_refund_price() + ((TextUtils.isEmpty(shProductBean.getSh_integral())
//                        ||TextUtils.isEmpty(shProductBean.getSh_integral_deduction())
//                        || (Long.parseLong(shProductBean.getSh_integral())+Long.parseLong(shProductBean.getSh_integral_deduction())) == 0)
//                        ? "" : ("+" + (Long.parseLong(shProductBean.getSh_integral())+Long.parseLong(shProductBean.getSh_integral_deduction())) + "金币")));
                tvMostReturn.setText("(最多" + StringsUtils.keep2num(mostPay_price+"") + "元)");
                etThirdReturn.setText(StringsUtils.keep2num(mostPay_price + ""));
                tvMosthbReturn.setText("(最多" + StringsUtils.keep2num(mostRedPack+"") + "元)");
                etHbReturn.setText(StringsUtils.keep2num(mostRedPack + ""));

                tvMostbalanceReturn.setText("(最多" + StringsUtils.keep2num(mostBalance+"") + "元)");
                etBalanceReturn.setText(StringsUtils.keep2num(mostBalance + ""));
                tvMostintegralReturn.setText("(最多" + (mostIntegral) + ")");
                etIntegralReturn.setText(mostIntegral + "");
                tvMostintegralReturnDeduction.setText("(最多" + (mostIntegralDeduction) + ")");
                etIntegralReturnDeduction.setText(mostIntegralDeduction + "");
//                    }
            }
        }

        if (dataBean.getSh_refund_info() != null && !TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_id())) {

            for (int i = 0; i < dataBean.getSh_receive_status_list().size(); i++) {
                ReturnGoodsBean.DataBean.ShReceiveStatusListBean receiveStatus = dataBean.getSh_receive_status_list().get(i);
                if (receiveStatus.getSh_status_id().equals(dataBean.getSh_refund_info().getSh_receive_status())) {
                    receiveIndex = i;
                    reasonList = i == 0 ?dataBean.getSh_new_reason().getSh_refund().getSh_no_received():dataBean.getSh_new_reason().getSh_refund().getSh_is_received();
                    tvShipment.setText(receiveStatus.getSh_status_text());
                    if (!receiveStatus.getSh_status_id().equals(receive_status)){
                        tvReason.setText("请选择");
                        resean_id = "";
                    }
                    receive_status = receiveStatus.getSh_status_id();
                    break;
                }
            }

            //设置原因
            for (ReturnGoodsBean.DataBean.ShReasonBean reason : reasonList) {
                if (reason.getSh_relation_id().equals(dataBean.getSh_refund_info().getSh_relation_id())) {
                    tvReason.setText(reason.getSh_reason_name());
                    resean_id = reason.getSh_relation_id();
                    refund_reason_id = reason.getSh_refund_reason_id();
                    refund_type_id = reason.getSh_refund_type_id();
                    break;
                }
            }
            etDesc.setText(dataBean.getSh_refund_info().getSh_description());
            etThirdReturn.setText(StringsUtils.keep2num(dataBean.getSh_refund_info().getSh_amount()));
            etHbReturn.setText(StringsUtils.keep2num(dataBean.getSh_refund_info().getSh_bupiao_amount()));
            etBalanceReturn.setText(StringsUtils.keep2num(dataBean.getSh_refund_info().getSh_balance_amount()));
            etIntegralReturn.setText(dataBean.getSh_refund_info().getSh_integral());
            etIntegralReturnDeduction.setText(dataBean.getSh_refund_info().getSh_integral_deduction());

            //退快递费
            if (!TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_is_refund_shipping())){
                tvFreightCheck.setChecked("1".equals(dataBean.getSh_refund_info().getSh_is_refund_shipping()));
            }

            if (dataBean.getSh_refund_info().getSh_images() != null && dataBean.getSh_refund_info().getSh_images().size() > 0) {
                int i = 1;
                for (ReturnGoodsBean.DataBean.ShRefundInfoBean.ShImagesBean imagesBean : dataBean.getSh_refund_info().getSh_images()) {
                    UploadImgBean.DataBean dataBean1 = new UploadImgBean.DataBean();
                    dataBean1.setSh_image_url(imagesBean.getSh_url());
                    dataBean1.setSh_name(imagesBean.getSh_url());
                    images.add(dataBean1);
                    if (IMAGE_SIZE <= images.size()) {
                        rlAddImg.setVisibility(View.GONE);
                    }
                    View imageItem = View.inflate(mContext, R.layout.item_img, null);
                    ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.getLayoutParams().height = imageHeight;
                    imageView.getLayoutParams().width = imageHeight;
                    ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                    iv_delete.setTag(dataBean1.getSh_image_url());
                    iv_delete.setOnClickListener(v -> {
                        gridLayout.removeView(imageItem);
//                        if (IMAGE_SIZE > images.size()) {
                            rlAddImg.setVisibility(View.VISIBLE);
//                        }
                        removeImage((String) iv_delete.getTag());
                    });
                    ViewTransformUtil.glideImageView(ReturnMoneyActivity.this, dataBean1.getSh_image_url(), imageView, new Transformation[]{
                            new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);

//                    ViewTransformUtil.glideImageView(ReturnMoneyActivity.this,dataBean1.getSh_image_url(),imageView,R.mipmap.defaults);

                    gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                    i++;
                }
            }
        }

        //退快递费
        ReturnGoodsBean.DataBean.ShRefundShipping refundShipping = dataBean.getSh_refund_shipping();
        if (refundShipping!=null&&!TextUtils.isEmpty(refundShipping.getSh_show_amount())){
            tvFreightPrice.setData("0",refundShipping.getSh_show_amount());
            SpannableString spannableString = new SpannableString(new StringBuffer("已支付¥").append(refundShipping.getSh_show_amount()).append("，仅支持全部退回").toString());
            spannableString.setSpan(new RelativeSizeSpan(0.73f), 3, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            tvFreightDesc.setText(spannableString);
            layoutFreight.setVisibility(!TextUtils.isEmpty(refundShipping.getSh_show_refund_shipping())&&"1".equals(
                    refundShipping.getSh_show_refund_shipping())?View.VISIBLE:View.GONE);
        }else {
            layoutFreight.setVisibility(View.GONE);
        }

    }


    @SuppressLint("CheckResult")
    @Override
    public void applyAfterSaleSuccess() {
        dismiss_progressDialog();
        returnDialog.dismiss();
        RxBus.$().post(Config.AFTERSALE_REFRESH);
        setResult(ChooseAfterSaleActivity.RESULT_SUCCESS);
        Observable.just("s").delay(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(s -> {
            if (!TextUtils.isEmpty(product_id) && !"0".equals(product_id)) {
                if ("purchase".equals(fromType)){
                    ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_DETAIL_ACTIVITY)
                            .withString("order_product_id",product_id)
                            .withString("order_id", order_id).navigation();
                }else {
                    startActivitry(AfterSaleDetailActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"type", NEW_AFTERSALE}});
                }
            } else {
                if ("purchase".equals(fromType)){
                    ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_LIST_ACTIVITY).navigation();
                }else {
                    startActivitry(AfterSaleListActivity.class, null);
                }
            }
            finish();
//            if (ChooseAfterSaleActivity.instance != null) {
//                ChooseAfterSaleActivity.instance.finish();
//            }
        });
    }

    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean) {
        if (images == null) {
            images = new ArrayList<>();
        }
        images.add(dataBean);
        if (IMAGE_SIZE <= images.size()) {
            rlAddImg.setVisibility(View.GONE);
        }
    }

    private void removeImage(String name) {
        int p = -1;
        for (int i = 0; i < images.size(); i++) {
            if (name.equals(images.get(i).getSh_name())) {
                p = i;
                break;
            }
        }

        if (p > -1) {
            images.remove(p);
        }
    }

    @Override
    public void showError(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void showError(String code, String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }
}
